package lian_xi;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

class  Account{
    private String name;
    private Long asset;
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public Account(String name,Long asset){
        this.name = name;
        this.asset = asset;
    }
    public void save(int asset){
        this.readWriteLock.writeLock().lock();
        try{
            this.asset += asset;
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+"存钱成功，余额为："+this.asset);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            this.readWriteLock.writeLock().unlock();
        }
    }

    public String toString(){
        this.readWriteLock.writeLock().lock();
        try {
            TimeUnit.SECONDS.sleep(100);
            return "【账户信息】："+this.name+"，余额为："+this.asset;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            this.readWriteLock.writeLock().unlock();
        }
    }
}

public class ReentrantReadWriteLock {

    public static void main(String[] args) {
        Account account = new Account("余睿恒", 999999999L);
        int money[] = new int[]{100,200,300};
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0){
                new Thread(()->{
                    for (int j = 0; j < money.length; j++) {
                        account.save(money[j]);
                    }
                },"【存钱线程】"+i).start();
            }else {
                new Thread(()->{
                    while (true) {
                        System.out.println(account);
                    }
                },"【取钱线程】"+i).start();
            }
        }
    }

    public Lock writeLock() {
        return null;
    }
}
